package com.samuel.basics.config;

import org.elasticsearch.client.RestHighLevelClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.client.ClientConfiguration;
import org.springframework.data.elasticsearch.client.RestClients;
import org.springframework.data.elasticsearch.config.AbstractElasticsearchConfiguration;
import org.springframework.http.HttpHeaders;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * <p>ES的相关配置</p>
 *
 * @author aneng huang
 * @since 2020-12-24 19:30:30
 */
@Configuration
public class ElasticSearchConfig extends AbstractElasticsearchConfiguration {

    private static final Logger logger = LoggerFactory.getLogger(ElasticSearchConfig.class);


    /**
     * 配置高级ES客户端
     * @return ES客户端
     */
    @Override
    public RestHighLevelClient elasticsearchClient() {
    	logger.info("设置ES客户端");
        // 默认标题相关的配置
        HttpHeaders defaultHeaders = new HttpHeaders();
        ClientConfiguration clientConfiguration = ClientConfiguration.builder()
                // 设置集群连接
                .connectedTo("localhost:9200", "localhost:9201")
                // 启用SSL (可选)
                // .usingSsl()
                // 启动代理 (可选)
                // .withProxy("localhost:8888")
                // 设置路径前缀，该路径前缀通常在不同集群在某个反向代理后面时使用。(可选)
                // .withPathPrefix("ela")
                // 连接连接超时 默认10秒
                .withConnectTimeout(Duration.ofMillis(5))
                // 设置套接字超时。默认值为5秒。
                .withSocketTimeout(Duration.ofMillis(5))
                // 可选）设置标题。
                .withDefaultHeaders(defaultHeaders)
                // Supplier<Header>可以指定一个函数，该函数在每次将请求发送到Elasticsearch之前都会被调用-例如，此处将当前时间写入标头中
                .withHeaders(() -> {
                    HttpHeaders headers = new HttpHeaders();
                    headers.add("currentTime", LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
                    return headers;
                })
                .build();

        return RestClients.create(clientConfiguration).rest();
    }
}
